package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



import dao.CommentDao;
import dao.GoodsDao;
import dao.LableDao;
import dao.UserDao;
import entity.Comment;
import entity.Goods;
import entity.User;




@WebServlet("/shoplist")
public class ShoplistServlet extends HttpServlet {
	GoodsDao goodsDao = new GoodsDao();
	LableDao lableDao = new LableDao();
//	querBylIdGoods
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");//这是一个坑，前端传数据进来，要先判断它编码是否正确
		resp.setContentType("text/html;charset=UTF-8");//防止中文乱码
        // 获取Session中的用户uid
        HttpSession session = req.getSession();
        String ud = (String) session.getAttribute("uid");
        
		String s = req.getParameter("s");
		
		int uid = Integer.parseInt(ud);		
		int lid;
		//获取dao对象	
		List<Goods> allList = null;//所有的记录		
		List<Goods> pageList = null;//当前页的记录
		int nowPage = 1;//当前页
		int totalPage = 0;//总页数
		int pageNum =3;   //一页的数量		

		if(s.equals("1")) {  //模糊查询
			String search = req.getParameter("search");
			try {
				pageList = goodsDao.querBylikeGoods(search);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}else if(s.equals("2")) { //条件查询，通过标签id
			String ld = req.getParameter("lid");
			lid = Integer.parseInt(ld);	
			try {
				pageList = lableDao.querBylIdGoods(lid);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else {  //查询所有,含分页查询
			//查看当前page有没有参数，没有说明是第一次访问
			if(req.getParameter("page")==null) {
				try {
					allList = goodsDao.queryAll();//查所有记录
					totalPage = allList.size()/pageNum+1;//总页数
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}else {
				nowPage = Integer.valueOf(req.getParameter("page"));//获取当前页
				totalPage = (int) session.getAttribute("totalPage");//获取总页数
			}
			
			//查当前页
			try {
				pageList = goodsDao.queryAllByPage(nowPage,pageNum);
				System.out.println(pageList.size());
			} catch (SQLException e) {
				e.printStackTrace();
			}			
		}
		
		//存到请求域
		req.setAttribute("glist", pageList);
		session.setAttribute("nowPage", nowPage);
		session.setAttribute("totalPage", totalPage);
		
		try {
			req.getRequestDispatcher("shoplist.jsp").forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	//获取所有商品
	
}